from rest_framework import serializers
from drf_haystack.serializers import HaystackSerializer

from goods.models import SKU
from goods.search_indexes import SKUIndex
from django_redis import get_redis_connection


class GoodsSerializers(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'


class SKUIndexSerializer(HaystackSerializer):
    object = GoodsSerializers(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')


class UserGoodsHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    # serializers.CharField(min_length=)

    def validate(self, attrs):
        # 判断id对应的商品是否存在
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs

    def create(self, validated_data):
        # 保存id数据到redis
        user = self.context['request'].user

        # 建立连接对象
        conn = get_redis_connection('history')
        # 判断重复数据,进行删除
        conn.lrem('history_%s' % user.id,0,validated_data['sku_id'])
        # 写入
        conn.lpush('history_%s' % user.id,validated_data['sku_id'])
        # 控制列表数据的数量
        conn.ltrim('history_%s' % user.id,0,4)

        return validated_data
